package data

import (
	"fmt"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/core/db"
)

// 初始化任务数据库
func InitTaskDbData() (err error) {
	taskDb := db.Model(&model.AdminTask{})
	tableName := taskDb.GetTableName()
	// 创建数据表
	tableSql := "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
		"`id` bigint unsigned NOT NULL," +
		"`member_id` int unsigned NOT NULL DEFAULT '0' COMMENT '创建成员id'," +
		"`type` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '类型。11 数据导出'," +
		"`title` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '标题'," +
		"`snap` json DEFAULT NULL COMMENT '执行快照'," +
		"`rate` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '进度。百分比'," +
		"`latency` bigint unsigned NOT NULL DEFAULT '0' COMMENT '耗时（单位：ms）'," +
		"`status` tinyint unsigned NOT NULL DEFAULT '11' COMMENT '状态。11 等待执行、22 执行中、33 执行完成、44 执行失败、55 已取消'," +
		"`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP," +
		"`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP," +
		"PRIMARY KEY (`id`) USING BTREE," +
		"KEY `idx_member_id` (`member_id`) USING BTREE," +
		"KEY `idx_created_at` (`created_at`) USING BTREE" +
		") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='后台任务表';"
	err = global.MySQL.Exec(tableSql).Error
	if err != nil {
		err = fmt.Errorf("创建数据表%s失败！%v", tableName, err)
	}
	return
}
